<template>
	<cl-page>
		<view class="page">
			<!-- 自定义状态栏 -->
			<cl-status-bar />

			<cl-sticky>
				<!-- 搜索栏 -->
				<cl-topbar :border="false" :show-back="false" :ref="setRefs('topbar')" :padding="0">
					<cl-search
						v-model="keyWord"
						placeholder="商品名称|生产厂家|商品助记码|通用名"
						@search="refresh({ page: 1 })"
					>
						<template #prepend>
							<cl-icon name="arrow-left" size="22px" @tap="refs.topbar?.back" />
						</template>
					</cl-search>
				</cl-topbar>

				<!-- 筛选栏 -->
				<filter-bar @search="refresh" :ref="setRefs('filterBar')" />
			</cl-sticky>

			<!-- 商品列表 -->
			<view class="list">
				<cl-waterfall :ref="setRefs('list')" :column="2">
					<template #default="{ list }">
						<cl-waterfall-column v-for="(columns, index) in list" :key="index">
							<enhanced-goods-item
								v-for="item in columns"
								:key="item.id"
								:item="item"
								@click="toGoodsDetail"
								@add-cart="addToCart"
								@collect="toggleCollect"
							/>
						</cl-waterfall-column>
					</template>
				</cl-waterfall>
			</view>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { onReady } from "@dcloudio/uni-app";
import { useCool, usePager } from "/@/cool";
import { useStore } from "/@/cool/store";
import EnhancedGoodsItem from "/@/components/goods/enhanced-item.vue";
import FilterBar from "./components/filter-bar.vue";

const { router, service, refs, setRefs } = useCool();
const { onRefresh, onData } = usePager();
const { user: userStore } = useStore();

const keyWord = ref("");

// 获取列表
function refresh(params?: any) {
	const { data, next } = onRefresh(params);

	onData((list) => {
		if (data.page == 1) {
			refs.list.refresh(list);
		} else {
			refs.list.append(list);
		}
	});

	// 从路由参数中获取attribute
	const attribute = router.query.attribute ? [Number(router.query.attribute)] : undefined;

	return next(
		service.goods.info.page({
			...data,
			keyWord: keyWord.value.toUpperCase(),
			attribute: attribute,
			subTitle: "YES",
		})
	);
}

onReady(() => {
	keyWord.value = router.query.keyWord?.toUpperCase() || "";

	// 延迟一下以确保filter-bar已经初始化完成
	setTimeout(() => {
		// 获取filter-bar的筛选条件
		const filterParams = refs.filterBar?.getSearchParams() || {};
		refresh({
			order: "sortNum",
			sort: "desc",
			...router.query,
			...filterParams,
		});
	}, 100);
});

// 商品详情页跳转
function toGoodsDetail(item: any) {
	router.push(`/pages/goods/detail?id=${item.id}`);
}

// 添加到购物车
async function addToCart(item: any) {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	try {
		await service.order.cart.addCart({
			goodsId: item.goodsId,
			count: 1,
		});

		uni.showToast({
			title: "添加成功",
			icon: "success",
		});
	} catch (error) {
		uni.showToast({
			title: "添加失败",
			icon: "error",
		});
	}
}

// 收藏/取消收藏
async function toggleCollect(item: any) {
	if (!userStore.token) {
		router.push("/pages/user/login");
		return;
	}

	try {
		if (item.isCollected) {
			await service.user.collect.delete({ ids: [item.id] });
		} else {
			await service.user.collect.collect({ goodsId: item.id });
		}

		uni.showToast({
			title: item.isCollected ? "取消收藏" : "收藏成功",
			icon: "success",
		});

		item.isCollected = !item.isCollected;
	} catch (error) {
		uni.showToast({
			title: "操作失败",
			icon: "error",
		});
	}
}

defineExpose({
	refresh,
});
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background-color: #f5f5f5;

	.list {
		padding: 24rpx 16rpx;
		background-color: #f5f5f5;
	}

	:deep(.cl-sticky) {
		padding-top: 20rpx;
		background-color: #fff;
	}

	:deep(.cl-topbar) {
		background-color: #fff;
		padding: 16rpx 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	:deep(.cl-search) {
		flex: 1;

		.cl-input {
			background-color: #f5f5f5;
			border-radius: 36rpx;
		}
	}

	// 瀑布流优化
	:deep(.cl-waterfall) {
		.cl-waterfall-column {
			.enhanced-goods-item {
				margin-bottom: 24rpx;

				.goods-card {
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
					transition: all 0.3s ease;

					&:active {
						transform: scale(0.98);
						box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.12);
					}
				}
			}
		}
	}
}
</style>
